#include <STC89C5xRC.H>

sbit LCD_RS=P2^6;
sbit LCD_RW=P2^5;
sbit LCD_E=P2^7;
#define LCD_dataport  P0

void LCD_Delay(void)	//@11.0592MHz 1ms
{
	unsigned char i, j;

	i = 2;
	j = 199;
	do
	{
		while (--j);
	} while (--i);
}


void lcd_writecommand(unsigned char command)
{
	LCD_RS=0;
	LCD_RW=0;
	LCD_dataport=command;
	LCD_E=1;
	LCD_Delay();
	LCD_E=0;
	LCD_Delay();
	
}

void lcd_writedata(unsigned char Data)
{
	LCD_RS=1;
	LCD_RW=0;
	LCD_dataport=Data;
	LCD_E=1;
	LCD_Delay();
	LCD_E=0;
	LCD_Delay();
}

void lcd_init()
{
	lcd_writecommand(0x38);
	lcd_writecommand(0x0c);
	lcd_writecommand(0x06);
	lcd_writecommand(0x01);
}

//设置光标
void lcd_setAC(unsigned char line, unsigned char col)
{
	if(line==1)
	{
		lcd_writecommand(0x80|(col-1));
	}
	else
	{
		lcd_writecommand(0x80|(col-1)+0x40);
	}
}

void lcd_showchar(unsigned char line, unsigned char col,unsigned char Char)
{
	lcd_setAC(line,col);
	lcd_writedata(Char);
}

void lcd_showstring(unsigned char line, unsigned char col,unsigned char* string)
{
	unsigned char i;
	lcd_setAC(line,col);
	for(i=0;string[i] != '\0';i++)
	{
		lcd_writedata(string[i]);
	}
}

int lcd_pow(int x,int y)
{
	unsigned char i;
	int ret=1;
	for(i = 0;i<y;i++)
	{
		ret*=x;
	}
	return ret;
}

void lcd_shownum(unsigned char line, unsigned char col,unsigned int num,unsigned char lenth)
{
	unsigned char i;
	lcd_setAC(line,col);
	for(i=lenth;i>0;i--)
	{
		lcd_writedata('0'+(num/lcd_pow(10,(i-1))%10));
	}
}

void lcd_showsignednum(unsigned char line, unsigned char col,int num,unsigned char lenth)
{
	unsigned char i;
	unsigned int shownum;
	lcd_setAC(line,col);
	if(num>=0)
	{
		lcd_writedata('+');
		shownum=num;
	}
	else
	{
		lcd_writedata('-');
		shownum=-num;
	}
	for(i=lenth;i>0;i--)
	{
		lcd_writedata('0'+(shownum/lcd_pow(10,(i-1))%10));
	}
}

void lcd_showhexnum(unsigned char line, unsigned char col,unsigned int num,unsigned char lenth)
{
	unsigned char i;
	unsigned char singlenum;
	lcd_setAC(line,col);
	for(i=lenth;i>0;i--)
	{
		singlenum=num/lcd_pow(16,(i-1))%16;
		if(singlenum<10)
		{
			lcd_writedata('0'+singlenum);
		}
		else
		{
			lcd_writedata('A'+singlenum%10);
		}
	}
}

void lcd_showbinnum(unsigned char line, unsigned char col,unsigned int num,unsigned char lenth)
{
	unsigned char i;
	lcd_setAC(line,col);
	for(i=lenth;i>0;i--)
	{
		lcd_writedata('0'+(num/lcd_pow(2,(i-1))%2));
	}
}

